/**
 *    Copyright 2010 Merrick Zhang ( anphorea@gmail.com )
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */
package anpho.proxyvalidator.config;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Merrick
 * 
 */
public class AppContext {

	final static String DEFAULT_CONFIG = "settings.properties";
	/**
	 * Logger of slf4j
	 */
	static Logger log = LoggerFactory.getLogger(AppContext.class);

	/**
	 * the properties
	 */
	static Properties p = new Properties();

	/**
	 * Load settings from file
	 * 
	 * @param f
	 *            the classpath of file
	 */
	public static void loadFromFile(String f) {

		InputStream fis = null;
		try {
			fis = Thread.currentThread().getContextClassLoader()
					.getResourceAsStream(f);
			p.load(fis);
		} catch (FileNotFoundException e) {
			log.error("File Not Found : {}", f);
		} catch (IOException e) {
			log.error("Properties Load Failed : {}", e.getMessage());
		} finally {
			if (null != fis) {
				try {
					fis.close();
				} catch (IOException e) {
					log.error("Close File Failed : {}", e.getMessage());
				}
			}
		}
	}

	/**
	 * get configured value from properties
	 * 
	 * @param key
	 * @return
	 */
	public static Object get(Object key) {
		if (null == p || p.size() == 0) {
			loadFromFile(DEFAULT_CONFIG);
		}
		return p.get(key);
	}

	/**
	 * This method will return 0 if there is no such a configuration
	 * item.Otherwise an Int is returned.
	 * 
	 * @param key
	 * @return
	 */
	public static int getInt(Object key) {
		if (null == p || p.size() == 0) {
			loadFromFile(DEFAULT_CONFIG);
		}
		String i = (String) p.get(key);
		try {
			return Integer.parseInt(i);
		} catch (Exception e) {
			return 0;
		}
	}

	/**
	 * This method will return null if there is no such a configuration
	 * item.otherwise a String is returned.
	 * 
	 * @param key
	 * @return
	 */
	public static String getStr(Object key) {
		if (null == p || p.size() == 0) {
			loadFromFile(DEFAULT_CONFIG);
		}
		return (String) p.get(key);
	}

}
